/**
 * Project:mail-settings-detector
 * File:DnsUtils.java
 * Copyright 2004-2014 Homolo Co., Ltd. All rights reserved.
 */
package com.homolo.msd.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xbill.DNS.*;

import java.util.Arrays;
import java.util.Comparator;

/**
 * The dns record utility class.
 *
 * @author rory
 */
public final class DnsUtils {

    /**
     * The slf4j logger.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(DnsUtils.class);

    /**
     * private constructor for non instance this class.
     */
    private DnsUtils() {
    }

    /**
     * get the domain's MX records.
     *
     * @param domain the domain to get.
     * @return the MX record array or null when not found any.
     */
    public static final String[] getMXRecords(String domain) {
        try {
            Record[] records = new Lookup(domain, Type.MX).run();
            if (records != null) {
                Arrays.sort(records, new Comparator<Record>() {
                    public int compare(Record r1, Record r2) {
                        return ((MXRecord) r1).getPriority() - ((MXRecord) r2).getPriority();
                    }
                });
                String[] array = new String[records.length];
                convertToStringArray(records, array);
                return array;
            }
        } catch (TextParseException e) {
            LOGGER.error("getMXRecords error.", e);
        }
        return new String[]{};
    }

    /**
     * convert the Record to string array.
     * 
     * @param records the dns records
     * @param array the record string array
     */
    private static void convertToStringArray(Record[] records, String[] array) {
        for (int i = 0; i < records.length; i++) {
            String recordString = ((MXRecord) records[i]).getTarget().toString();
            if (recordString.endsWith(".")) {
                array[i] = recordString.substring(0, recordString.length() - 1);
            } else {
                array[i] = recordString;
            }
        }
    }

}
